{{template "base" .}}

{{define "content"}}
<div x-data="newCustomerData()" class="space-y-6">
    <!-- Page Header -->
    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
        <div>
            <h1 class="text-xl font-semibold text-gray-900">添加客户</h1>
            <p class="mt-1 text-sm text-gray-500">录入新客户的基本信息和学习需求</p>
        </div>
        <div class="mt-3 sm:mt-0">
            <a href="/customers" 
               class="inline-flex items-center px-3 py-2 bg-gray-500 text-white text-sm rounded-md hover:bg-gray-600 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
                <i class="fas fa-arrow-left text-sm mr-2"></i>
                返回列表
            </a>
        </div>
    </div>

    <!-- Progress Indicator -->
    <div class="bg-white rounded-md shadow-sm p-3 border border-gray-200">
        <div class="flex items-center justify-between mb-2">
            <span class="text-sm font-medium text-gray-700">填写进度</span>
            <span class="text-sm font-semibold" :class="progress === 100 ? 'text-green-600' : 'text-blue-600'" x-text="Math.round(progress) + '%'"></span>
        </div>
        <div class="w-full bg-gray-200 rounded-full h-1.5">
            <div class="h-1.5 rounded-full transition-all duration-300 ease-out" 
                 :class="progress === 100 ? 'bg-green-500' : 'bg-blue-500'"
                 :style="'width: ' + progress + '%'"></div>
        </div>
    </div>

    <!-- Form -->
    <div class="bg-white shadow-sm rounded-md border border-gray-200">
        <form @submit.prevent="submitForm()" class="space-y-0">
            <!-- 基本信息区域 -->
            <div class="px-4 py-3 border-b border-gray-200 bg-gray-50 rounded-t-md">
                <div class="flex items-center">
                    <div class="w-6 h-6 bg-blue-500 rounded-full flex items-center justify-center mr-3">
                        <i class="fas fa-user text-white text-sm"></i>
                    </div>
                    <div>
                        <h3 class="text-sm font-medium text-gray-900">基本信息</h3>
                        <p class="text-xs text-gray-500">请填写客户的基本信息</p>
                    </div>
                </div>
            </div>
            
            <div class="px-4 py-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- 姓名 -->
                    <div class="relative">
                        <label for="name" class="block text-sm font-medium text-gray-700 mb-1">
                            姓名 <span class="text-red-500">*</span>
                            <span class="text-gray-500 text-xs ml-1">(必填) - 请输入客户的真实姓名，用于身份识别和联系</span>
                        </label>
                        <input type="text" 
                               id="name"
                               x-model="form.name" 
                               @blur="validateField('name')"
                               @input="validateField('name')"
                               :class="getFieldClass('name')"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                               placeholder="请输入客户姓名"
                               autocomplete="name">
                        <p x-show="errors.name" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.name"></span>
                        </p>
                    </div>

                    <!-- 手机号 -->
                    <div class="relative">
                        <label for="phone" class="block text-sm font-medium text-gray-700 mb-1">
                            手机号
                            <span class="text-gray-500 text-xs ml-1">(选填) - 请输入11位有效手机号码，用于课程通知和联系</span>
                        </label>
                        <input type="tel" 
                               id="phone"
                               x-model="form.phone" 
                               @blur="validateField('phone')"
                               @input="validateField('phone')"
                               :class="getFieldClass('phone')"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                               placeholder="请输入手机号"
                               autocomplete="tel">
                        <p x-show="errors.phone" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.phone"></span>
                        </p>
                    </div>

                    <!-- 微信 -->
                    <div class="relative">
                        <label for="wechat" class="block text-sm font-medium text-gray-700 mb-1">
                            微信号
                            <span class="text-gray-500 text-xs ml-1">(选填) - 客户的微信账号</span>
                        </label>
                        <input type="text" 
                               id="wechat"
                               x-model="form.wechat" 
                               @blur="validateField('wechat')"
                               :class="getFieldClass('wechat')"
                               class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 text-sm"
                               placeholder="请输入微信账号">
                        <p x-show="errors.wechat" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.wechat"></span>
                        </p>
                    </div>

                    
                     <!-- 年级 -->
                    <div class="relative">
                        <label for="grade" class="block text-sm font-medium text-gray-700 mb-1">
                            年级
                            <span class="text-gray-500 text-xs ml-1">(选填) - 请选择客户当前就读年级，用于匹配合适的课程内容</span>
                        </label>
                        <div class="relative">
                            <select id="grade"
                                    x-model="form.grade" 
                                    @blur="validateField('grade')"
                                    @change="validateField('grade')"
                                    :class="getFieldClass('grade')"
                                    class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 appearance-none cursor-pointer text-sm">
                                <option value="">请选择年级</option>
                                <optgroup label="小学">
                                    <option value="小学一年级">小学一年级</option>
                                    <option value="小学二年级">小学二年级</option>
                                    <option value="小学三年级">小学三年级</option>
                                    <option value="小学四年级">小学四年级</option>
                                    <option value="小学五年级">小学五年级</option>
                                    <option value="小学六年级">小学六年级</option>
                                </optgroup>
                                <optgroup label="初中">
                                    <option value="初中一年级">初中一年级</option>
                                    <option value="初中二年级">初中二年级</option>
                                    <option value="初中三年级">初中三年级</option>
                                </optgroup>
                                <optgroup label="高中">
                                    <option value="高中一年级">高中一年级</option>
                                    <option value="高中二年级">高中二年级</option>
                                    <option value="高中三年级">高中三年级</option>
                                </optgroup>
                                <optgroup label="其他">
                                    <option value="大学">大学</option>
                                    <option value="成人">成人</option>
                                </optgroup>
                            </select>
                        </div>
                        <p x-show="errors.grade" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.grade"></span>
                        </p>
                    </div>


                    <!-- 年龄 -->
                    <div class="relative">
                        <label for="age" class="block text-sm font-medium text-gray-700 mb-1">
                            年龄
                            <span class="text-gray-500 text-xs ml-1">(可选) - 请输入客户年龄，有助于制定合适的学习计划</span>
                        </label>
                        <input type="number" 
                               id="age"
                               x-model="form.age" 
                               @blur="validateField('age')"
                               @input="validateField('age')"
                               min="1"
                               max="100"
                               :class="getFieldClass('age')"
                               class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 text-sm"
                               placeholder="请输入年龄"
                               autocomplete="age">
                        <p x-show="errors.age" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.age"></span>
                        </p>
                    </div>

                    <!-- 性别 -->
                    <div class="relative">
                        <label for="gender" class="block text-sm font-medium text-gray-700 mb-1">
                            性别
                            <span class="text-gray-500 text-xs ml-1">(可选) - 选择客户性别，便于安排合适的教学环境</span>
                        </label>
                        <select id="gender"
                                x-model="form.gender" 
                                @blur="validateField('gender')"
                                @change="validateField('gender')"
                                :class="getFieldClass('gender')"
                                class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 hover:border-gray-400 transition-colors duration-200 appearance-none text-sm cursor-pointer">
                            <option value="">请选择性别</option>
                            <option value="male">男</option>
                            <option value="female">女</option>
                        </select>
                    </div>
            
                    <!-- 城市 -->
                    <div class="relative">
                        <label for="city" class="block text-sm font-medium text-gray-700 mb-1">
                            城市 <span class="text-red-500">*</span>
                            <span class="text-gray-500 text-xs ml-1">(必填) - 请选择客户所在城市，用于安排就近的教学点</span>
                        </label>
                        
                        <!-- 热门城市快速选择 -->
                        <div class="mb-2">
                            <div class="text-sm text-gray-500 mb-1">热门城市</div>
                            <div class="flex flex-wrap gap-1">
                                <template x-for="(city, index) in ['北京', '上海', '广州', '深圳', '杭州', '南京', '苏州', '成都']" :key="city">
                                    <button type="button" 
                                            @click="form.city = city; validateField('city')"
                                            :class="form.city === city ? 'bg-blue-100 border-blue-300 text-blue-700' : 'bg-gray-100 border-gray-300 text-gray-600 hover:bg-blue-50 hover:text-blue-600'"
                                            class="px-2 py-1 text-xs font-medium border rounded transition-colors duration-200">
                                            <span x-text="city"></span>
                                    </button>
                                </template>
                            </div>
                        </div>
                        
                        <div class="relative" x-data="{ 
                            showDropdown: false, 
                            filteredCities: [], 
                            selectedIndex: -1,
                            searchQuery: '',
                            init() {
                                this.filteredCities = this.commonCities.slice(0, 10);
                            },
                            filterCities(query) {
                                this.searchQuery = query;
                                if (!query || query.trim() === '') {
                                    this.filteredCities = this.commonCities.slice(0, 10);
                                } else {
                                    const searchTerm = query.toLowerCase().trim();
                                    this.filteredCities = this.commonCities.filter(city => 
                                        city.toLowerCase().includes(searchTerm)
                                    ).slice(0, 12);
                                }
                                this.selectedIndex = -1;
                            },
                            selectCity(city) {
                                this.form.city = city;
                                this.showDropdown = false;
                                this.validateField('city');
                                this.selectedIndex = -1;
                            },
                            handleKeydown(event) {
                                if (!this.showDropdown) return;
                                
                                switch(event.key) {
                                    case 'ArrowDown':
                                        event.preventDefault();
                                        this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredCities.length - 1);
                                        break;
                                    case 'ArrowUp':
                                        event.preventDefault();
                                        this.selectedIndex = Math.max(this.selectedIndex - 1, -1);
                                        break;
                                    case 'Enter':
                                        event.preventDefault();
                                        if (this.selectedIndex >= 0 && this.selectedIndex < this.filteredCities.length) {
                                            this.selectCity(this.filteredCities[this.selectedIndex]);
                                        }
                                        break;
                                    case 'Escape':
                                        this.showDropdown = false;
                                        this.selectedIndex = -1;
                                        break;
                                }
                            }
                        }" 
                        x-init="init()">
                            <div class="relative">
                                <input type="text" 
                                       id="city"
                                       x-model="form.city" 
                                       @input="filterCities($event.target.value); showDropdown = true; validateField('city')"
                                       @focus="showDropdown = true; filteredCities = commonCities.slice(0, 10)"
                                       @blur="setTimeout(() => showDropdown = false, 200)"
                                       @keydown="handleKeydown($event)"
                                       :class="getFieldClass('city')"
                                       class="w-full px-3 py-2 pr-10 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 text-sm"
                                       placeholder="输入城市名称搜索..."
                                       autocomplete="off">
                                
                                <!-- 搜索图标 -->
                                <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                    <i class="fas fa-search text-gray-400 text-sm"></i>
                                </div>
                            </div>
                            
                            <!-- 搜索下拉列表 -->
                            <div x-show="showDropdown && filteredCities.length > 0" 
                                 x-transition:enter="transition ease-out duration-200"
                                 x-transition:enter-start="opacity-0 transform scale-95 translate-y-1"
                                 x-transition:enter-end="opacity-100 transform scale-100 translate-y-0"
                                 x-transition:leave="transition ease-in duration-150"
                                 x-transition:leave-start="opacity-100 transform scale-100 translate-y-0"
                                 x-transition:leave-end="opacity-0 transform scale-95 translate-y-1"
                                 class="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl max-h-64 overflow-y-auto">
                                <div class="py-1">
                                    <template x-for="(city, index) in filteredCities" :key="city">
                                        <div @click="selectCity(city)"
                                             :class="{
                                                'bg-blue-50 text-blue-700': selectedIndex === index,
                                                'text-gray-900': selectedIndex !== index
                                             }"
                                             class="px-4 py-2.5 hover:bg-blue-50 hover:text-blue-700 cursor-pointer text-sm transition-colors duration-150 flex items-center justify-between group">
                                            <span x-text="city"></span>
                                            <i x-show="selectedIndex === index" class="fas fa-check text-blue-500 text-sm"></i>
                                        </div>
                                    </template>
                                </div>
                            </div>
                            
                            <!-- 无搜索结果提示 -->
                            <div x-show="showDropdown && form.city && form.city.trim() && filteredCities.length === 0" 
                                 x-transition
                                 class="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl p-4">
                                <div class="flex flex-col items-center justify-center text-gray-500 text-sm">
                                    <i class="fas fa-search text-gray-300 text-2xl mb-2"></i>
                                    <div class="text-center">
                                        <div class="font-medium">未找到匹配的城市</div>
                                        <div class="text-xs text-gray-400 mt-1">请尝试其他关键词</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <p x-show="errors.city" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.city"></span>
                        </p>
                    </div>

                    <!-- 地址 -->
                    <div class="relative">
                        <label for="address" class="block text-sm font-medium text-gray-700 mb-1">
                            地址
                            <span class="text-gray-500 text-xs ml-1">(选填) - 客户的详细地址信息</span>
                        </label>
                        <input type="text" 
                               id="address"
                               x-model="form.address" 
                               @blur="validateField('address')"
                               :class="getFieldClass('address')"
                               class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 text-sm"
                               placeholder="请输入详细地址">
                        <p x-show="errors.address" x-transition class="mt-1 text-xs text-red-600">
                            <span x-text="errors.address"></span>
                        </p>
                    </div>

                </div>

            </div>
            
            <!-- 学习信息区域 -->
            <div class="border-t border-gray-200">
                <div class="px-4 py-3 border-b border-gray-200 bg-gray-50">
                    <div class="flex items-center">
                        <div class="w-6 h-6 bg-green-500 rounded-full flex items-center justify-center mr-3">
                            <i class="fas fa-graduation-cap text-white text-sm"></i>
                        </div>
                        <div>
                            <h4 class="text-base font-semibold text-gray-900">学习信息</h4>
                            <p class="text-xs text-gray-600">请填写客户的学习需求和相关信息</p>
                        </div>
                    </div>
                </div>
                
                <div class="px-4 py-4">
                    <!-- 科目 -->
                    <div class="mb-4">
                        <div class="relative">
                            <label for="subject" class="block text-sm font-medium text-gray-700 mb-1">
                                学习科目 <span class="text-red-500">*</span>
                                <span class="text-gray-500 text-xs ml-1">(必填) - 请选择客户需要学习的科目，可选择多个科目</span>
                            </label>
                            
                            <!-- 热门科目快速选择 -->
                            <div class="mb-2">
                                <div class="text-xs text-gray-500 mb-1">热门科目</div>
                                <div class="flex flex-wrap gap-1">
                                    <template x-for="subject in ['数学', '英语', '语文', '物理', '化学', '生物']" :key="subject">
                                        <button type="button" 
                                                @click="form.subject = subject; validateField('subject')"
                                                :class="form.subject === subject ? 'bg-green-100 border-green-300 text-green-700' : 'bg-gray-100 border-gray-300 text-gray-600 hover:bg-green-50 hover:text-green-600'"
                                                class="px-2 py-1 text-xs font-medium border rounded transition-colors duration-200">
                                            <span x-text="subject"></span>
                                        </button>
                                    </template>
                                </div>
                            </div>
                            
                            <div class="relative" x-data="{ 
                                showDropdown: false, 
                                filteredSubjects: [], 
                                selectedIndex: -1,
                                searchQuery: '',
                                init() {
                                    this.filteredSubjects = this.commonSubjects.slice(0, 10);
                                },
                                filterSubjects(query) {
                                    this.searchQuery = query;
                                    if (!query || query.trim() === '') {
                                        this.filteredSubjects = this.commonSubjects.slice(0, 10);
                                    } else {
                                        const searchTerm = query.toLowerCase().trim();
                                        this.filteredSubjects = this.commonSubjects.filter(subject => 
                                            subject.toLowerCase().includes(searchTerm)
                                        ).slice(0, 12);
                                    }
                                    this.selectedIndex = -1;
                                },
                                selectSubject(subject) {
                                    this.form.subject = subject;
                                    this.showDropdown = false;
                                    this.validateField('subject');
                                    this.selectedIndex = -1;
                                },
                                handleKeydown(event) {
                                    if (!this.showDropdown) return;
                                    
                                    switch(event.key) {
                                        case 'ArrowDown':
                                            event.preventDefault();
                                            this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredSubjects.length - 1);
                                            break;
                                        case 'ArrowUp':
                                            event.preventDefault();
                                            this.selectedIndex = Math.max(this.selectedIndex - 1, -1);
                                            break;
                                        case 'Enter':
                                            event.preventDefault();
                                            if (this.selectedIndex >= 0 && this.selectedIndex < this.filteredSubjects.length) {
                                                this.selectSubject(this.filteredSubjects[this.selectedIndex]);
                                            }
                                            break;
                                        case 'Escape':
                                            this.showDropdown = false;
                                            this.selectedIndex = -1;
                                            break;
                                    }
                                }
                            }" 
                                 x-init="init()">
                                <div class="relative">
                                    <input type="text" 
                                           id="subject"
                                           x-model="form.subject" 
                                           @input="filterSubjects($event.target.value); showDropdown = true; validateField('subject')"
                                           @focus="showDropdown = true; filteredSubjects = commonSubjects.slice(0, 10)"
                                           @blur="setTimeout(() => showDropdown = false, 200)"
                                           @keydown="handleKeydown($event)"
                                           :class="getFieldClass('subject')"
                                           class="w-full px-3 py-2 pr-10 border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 text-sm"
                                           placeholder="输入科目名称搜索..."
                                           autocomplete="off">
                                    
                                    <!-- 搜索图标 -->
                                    <div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
                                        <i class="fas fa-search text-gray-400 text-sm"></i>
                                    </div>
                                </div>
                                
                                <!-- 搜索下拉列表 -->
                                <div x-show="showDropdown && filteredSubjects.length > 0" 
                                     x-transition:enter="transition ease-out duration-200"
                                     x-transition:enter-start="opacity-0 transform scale-95 translate-y-1"
                                     x-transition:enter-end="opacity-100 transform scale-100 translate-y-0"
                                     x-transition:leave="transition ease-in duration-150"
                                     x-transition:leave-start="opacity-100 transform scale-100 translate-y-0"
                                     x-transition:leave-end="opacity-0 transform scale-95 translate-y-1"
                                     class="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl max-h-64 overflow-y-auto">
                                    <div class="py-1">
                                        <template x-for="(subject, index) in filteredSubjects" :key="subject">
                                            <div @click="selectSubject(subject)"
                                                 :class="{
                                                    'bg-green-50 text-green-700': selectedIndex === index,
                                                    'text-gray-900': selectedIndex !== index
                                                 }"
                                                 class="px-4 py-2.5 hover:bg-green-50 hover:text-green-700 cursor-pointer text-sm transition-colors duration-150 flex items-center justify-between group">
                                                <span x-text="subject"></span>
                                                <i x-show="selectedIndex === index" class="fas fa-check text-green-500 text-sm"></i>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                                
                                <!-- 无搜索结果提示 -->
                                <div x-show="showDropdown && form.subject && form.subject.trim() && filteredSubjects.length === 0"
                                     x-transition
                                     class="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-xl p-4">
                                    <div class="flex flex-col items-center justify-center text-gray-500 text-sm">
                                        <i class="fas fa-search text-gray-300 text-2xl mb-2"></i>
                                        <div class="text-center">
                                            <div class="font-medium">未找到匹配的科目</div>
                                            <div class="text-xs text-gray-400 mt-1">请尝试其他关键词或手动输入</div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <p x-show="errors.subject" x-transition class="mt-1 text-xs text-red-600">
                                <span x-text="errors.subject"></span>
                            </p>
                        </div>
                    </div>

                    <!-- 备注 -->
                    <div class="mb-4">
                        <div class="relative">
                            <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">
                                备注信息
                                <span class="text-gray-500 text-xs ml-1">(可选) - 可填写客户的特殊需求、学习目标或其他重要信息</span>
                            </label>
                            <div class="relative">
                                <div class="relative">
                                    <textarea id="notes"
                                              x-model="form.notes" 
                                              @blur="validateField('notes')"
                                              @input="validateField('notes')"
                                              rows="3"
                                              :class="getFieldClass('notes')"
                                              class="w-full px-3 py-2.5 pr-16 border rounded-lg shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 hover:border-gray-400 transition-all duration-200 resize-none text-sm"
                                              placeholder="请输入备注信息（可选）"
                                              maxlength="200"></textarea>
                                    <div class="absolute bottom-2 right-2 text-xs text-gray-400">
                                        <span x-text="form.notes ? form.notes.length : 0"></span>/200
                                    </div>
                                </div>
                            </div>
                            <p x-show="errors.notes" x-transition class="mt-1 text-xs text-red-600">
                                <span x-text="errors.notes"></span>
                            </p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 提交按钮区域 -->
            <div class="border-t border-gray-100 bg-gray-50 px-4 py-3 rounded-b-lg">
                <div class="flex flex-col sm:flex-row justify-between items-center space-y-2 sm:space-y-0 sm:space-x-2">
                    <!-- 表单状态提示 -->
                    <div class="flex items-center text-xs">
                        <div class="flex items-center" x-show="hasErrors">
                            <span class="text-red-600">请检查并修正表单中的错误</span>
                        </div>
                        <div class="flex items-center" x-show="!hasErrors && isFormValid">
                            <span class="text-green-600">表单填写完整，可以提交</span>
                        </div>
                        <div class="flex items-center" x-show="!hasErrors && !isFormValid">
                            <span class="text-blue-600">请完善必填信息</span>
                        </div>
                    </div>
                    
                    <!-- 按钮组 -->
                    <div class="flex flex-col sm:flex-row space-y-2 sm:space-y-0 sm:space-x-3">
                        <!-- 草稿和取消按钮 -->
                        <div class="flex space-x-2">
                            <button type="button" 
                                    @click="saveDraft()"
                                    :disabled="loading"
                                    class="px-4 py-2 bg-yellow-500 text-white text-sm font-medium rounded-md hover:bg-yellow-600 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-yellow-500 focus:ring-offset-2 disabled:opacity-50">
                                <i class="fas fa-save text-sm mr-2"></i>
                                保存草稿
                            </button>
                        </div>
                        
                        <!-- 提交按钮 -->
                        <button type="submit" 
                                :disabled="loading || hasErrors"
                                :class="loading || hasErrors ? 'opacity-50 cursor-not-allowed' : 'hover:bg-blue-600'"
                                class="px-6 py-2 bg-blue-500 text-white text-sm font-medium rounded-md transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                            <i class="fas fa-check text-sm mr-2" x-show="!loading"></i>
                            <i class="fas fa-spinner fa-spin text-sm mr-2" x-show="loading"></i>
                            <span x-text="loading ? '保存中...' : '保存客户'"></span>
                        </button>
                    </div>
                </div>
            </div>
        </form>
    </div>


</div>

<script>
    function newCustomerData() {
        return {
            loading: false,
            form: {
                name: '',
                phone: '',
                age: null,
                gender: '',
                city: '',
                address: '',
                wechat: '',
                grade: '',
                subject: '',
                notes: ''
            },
            errors: {},
            commonCities: [
                '北京', '上海', '广州', '深圳', '杭州', '南京', '苏州', '成都', 
                '武汉', '西安', '重庆', '天津', '青岛', '大连', '厦门', '宁波',
                '无锡', '佛山', '东莞', '长沙', '郑州', '济南', '哈尔滨', '福州',
                '石家庄', '太原', '沈阳', '长春', '南昌', '合肥', '昆明', '贵阳',
                '兰州', '银川', '西宁', '乌鲁木齐', '拉萨', '海口', '三亚', '温州',
                '嘉兴', '绍兴', '金华', '台州', '湖州', '丽水', '衢州', '舟山',
                '常州', '徐州', '盐城', '淮安', '连云港', '南通', '泰州', '宿迁',
                '镇江', '扬州', '芜湖', '蚌埠', '安庆', '黄山', '阜阳', '宿州',
                '六安', '亳州', '池州', '宣城', '滁州', '马鞍山', '淮南', '淮北'
            ],
            commonSubjects: [
                '数学', '英语', '语文', '物理', '化学', '生物', '历史', '地理',
                '政治', '音乐', '美术', '体育', '信息技术', '科学', '思想品德',
                '编程', '机器人', '奥数', '作文', '阅读理解', '口语', '书法'
            ],
            popularSubjects: ['数学', '英语', '语文', '物理', '化学', '生物'],
            
            // 城市搜索过滤方法
            filterCities(query) {
                if (!query || query.trim() === '') {
                    this.filteredCities = this.commonCities.slice(0, 10); // 显示前10个城市
                    return;
                }
                
                const searchTerm = query.toLowerCase().trim();
                this.filteredCities = this.commonCities.filter(city => 
                    city.toLowerCase().includes(searchTerm)
                ).slice(0, 8); // 最多显示8个匹配结果
            },
            
            // 计算属性
            get progress() {
                const requiredFields = ['name', 'city', 'subject'];
                const optionalFields = ['phone', 'age', 'gender', 'grade', 'notes'];
                
                const filledRequired = requiredFields.filter(field => 
                    this.form[field] && this.form[field].toString().trim()
                ).length;
                const filledOptional = optionalFields.filter(field => 
                    this.form[field] && this.form[field].toString().trim()
                ).length;
                
                // 必填字段权重70%，可选字段权重30%
                const requiredProgress = (filledRequired / requiredFields.length) * 70;
                const optionalProgress = (filledOptional / optionalFields.length) * 30;
                
                return Math.min(100, Math.round(requiredProgress + optionalProgress));
            },
            
            get hasErrors() {
                return Object.keys(this.errors).length > 0;
            },
            
            get isFormValid() {
                const requiredFields = ['name', 'city', 'subject'];
                return requiredFields.every(field => this.form[field] && this.form[field].trim() && !this.errors[field]);
            },
            
            init() {
                try {
                    // 初始化时可以预填一些数据
                    const urlParams = new URLSearchParams(window.location.search);
                    if (urlParams.get('phone')) {
                        this.form.phone = urlParams.get('phone');
                    }
                    if (urlParams.get('name')) {
                        this.form.name = urlParams.get('name');
                    }
                    if (urlParams.get('city')) {
                        this.form.city = urlParams.get('city');
                    }
                    
                    // 尝试加载草稿
                    this.loadDraft();
                    
                    // 设置键盘快捷键
                    this.setupKeyboardShortcuts();
                    
                    // 设置自动保存
                    this.setupAutoSave();
                    
                    // 设置表单变化检测
                    this.setupFormChangeDetection();
                    
                    this.showNotification('页面加载完成，开始填写客户信息', 'info');
                } catch (error) {
                    console.error('初始化失败:', error);
                    this.showNotification('页面初始化失败', 'error');
                }
            },
            
            // 获取字段样式类
            getFieldClass(fieldName) {
                if (this.errors[fieldName]) {
                    return 'border-red-300 focus:border-red-500 focus:ring-red-500';
                } else if (this.form[fieldName] && this.form[fieldName].toString().trim()) {
                    return 'border-green-300 focus:border-green-500 focus:ring-green-500';
                } else {
                    return 'border-gray-300 focus:border-blue-500 focus:ring-blue-500';
                }
            },
            
            // 实时验证单个字段
            validateField(fieldName) {
                // 清除该字段的错误
                if (this.errors[fieldName]) {
                    delete this.errors[fieldName];
                }
                
                const value = this.form[fieldName];
                
                switch (fieldName) {
                    case 'name':
                        if (!value || !value.trim()) {
                            this.errors.name = '请输入客户姓名';
                        } else if (value.trim().length < 2) {
                            this.errors.name = '姓名至少需要2个字符';
                        }
                        break;
                        
                    case 'phone':
                        if (value && value.trim() && !this.isValidPhone(value.trim())) {
                            this.errors.phone = '请输入正确的手机号格式';
                        }
                        break;
                        
                    case 'city':
                        if (!value || !value.trim()) {
                            this.errors.city = '请输入所在城市';
                        }
                        break;
                        
                    case 'grade':
                        // 年级现在是可选的，只有当有值时才进行验证
                        if (value && value.trim() === '') {
                            this.errors.grade = '请选择年级';
                        }
                        break;

                    case 'subject':
                        if (!value || !value.trim()) {
                            this.errors.subject = '请输入学习科目';
                        }
                        break;
                        
                    case 'age':
                        if (value && (value < 1 || value > 100)) {
                            this.errors.age = '年龄必须在1-100之间';
                        }
                        break;
                        
                    case 'notes':
                        if (value && value.length > 500) {
                            this.errors.notes = '备注信息不能超过500个字符';
                        }
                        break;
                    case 'address':
                        if (value && value.length > 200) {
                            this.errors.address = '地址信息不能超过200个字符';
                        }
                        break;
                    case 'wechat':
                        if (value && value.length > 50) {
                            this.errors.wechat = '微信账号不能超过50个字符';
                        }
                        break;
                }
            },
            
            // 验证手机号格式
            isValidPhone(phone) {
                return /^1[3-9]\d{9}$/.test(phone);
            },
            
            // 设置键盘快捷键
            setupKeyboardShortcuts() {
                document.addEventListener('keydown', (e) => {
                    // Ctrl+Enter 提交表单
                    if (e.ctrlKey && e.key === 'Enter') {
                        e.preventDefault();
                        if (this.isFormValid && !this.loading) {
                            this.submitForm();
                        }
                    }
                    
                    // Ctrl+S 保存草稿
                    if (e.ctrlKey && e.key === 's') {
                        e.preventDefault();
                        this.saveDraft(true); // 手动保存显示提示
                    }
                    
                    // Esc 键返回列表
                    if (e.key === 'Escape') {
                        e.preventDefault();
                        if (this.hasFormData()) {
                            if (confirm('有未保存的数据，确定要离开吗？')) {
                                window.location.href = '/customers';
                            }
                        } else {
                            window.location.href = '/customers';
                        }
                    }
                });
            },
            
            // 设置自动保存
            setupAutoSave() {
                // 定期自动保存草稿
                setInterval(() => {
                    if (this.hasFormData()) {
                        this.saveDraft(false); // 自动保存不显示提示
                    }
                }, 60000); // 每分钟自动保存一次
            },
            
            // 设置表单变化检测
            setupFormChangeDetection() {
                // 监听页面离开事件
                window.addEventListener('beforeunload', (e) => {
                    if (this.hasFormData()) {
                        e.preventDefault();
                        e.returnValue = '有未保存的数据，确定要离开吗？';
                        return e.returnValue;
                    }
                });
            },
            
            // 检查是否有表单数据
            hasFormData() {
                const fieldsToCheck = ['name', 'phone', 'age', 'gender', 'city', 'address', 'wechat', 'grade', 'subject', 'notes'];
                return fieldsToCheck.some(field => {
                    const value = this.form[field];
                    return value !== null && value !== undefined && value.toString().trim() !== '';
                });
            },
            
            // 保存草稿到本地存储
            saveDraft(showNotification = true) {
                try {
                    if (!this.hasFormData()) {
                        return;
                    }
                    
                    const draftData = {
                        ...this.form,
                        timestamp: new Date().toISOString()
                    };
                    localStorage.setItem('customer_draft', JSON.stringify(draftData));
                    
                    // 显示成功提示
                    if (showNotification) {
                        this.showNotification('草稿已保存到本地', 'success');
                    }
                } catch (error) {
                    console.error('保存草稿失败:', error);
                    if (showNotification) {
                        this.showNotification('保存草稿失败', 'error');
                    }
                }
            },
            
            // 加载草稿
            loadDraft() {
                try {
                    const draftData = localStorage.getItem('customer_draft');
                    if (draftData) {
                        const draft = JSON.parse(draftData);
                        // 检查草稿是否在24小时内
                        const draftTime = new Date(draft.timestamp);
                        const now = new Date();
                        const hoursDiff = (now - draftTime) / (1000 * 60 * 60);
                        
                        if (hoursDiff < 24) {
                            delete draft.timestamp;
                            Object.assign(this.form, draft);
                            this.showNotification(`已加载 ${Math.round(hoursDiff)} 小时前的草稿数据`, 'info');
                            return true;
                        } else {
                            localStorage.removeItem('customer_draft');
                            this.showNotification('草稿已过期，已自动清理', 'warning');
                        }
                    }
                } catch (error) {
                    console.error('加载草稿失败:', error);
                    this.showNotification('加载草稿失败', 'error');
                }
                return false;
            },
            
            // 清除草稿
            clearDraft() {
                try {
                    localStorage.removeItem('customer_draft');
                    this.showNotification('草稿已清除', 'info');
                } catch (error) {
                    console.error('清除草稿失败:', error);
                }
            },
            
            // 显示通知
            showNotification(message, type = 'info') {
                // 移除现有通知
                const existingNotifications = document.querySelectorAll('.custom-notification');
                existingNotifications.forEach(n => n.remove());
                
                // 创建通知元素
                const notification = document.createElement('div');
                notification.className = `custom-notification fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg transition-all duration-300 transform translate-x-full max-w-sm`;
                
                const colors = {
                    success: 'bg-green-500 text-white border-green-600',
                    error: 'bg-red-500 text-white border-red-600',
                    info: 'bg-blue-500 text-white border-blue-600',
                    warning: 'bg-yellow-500 text-black border-yellow-600'
                };
                
                notification.className += ` ${colors[type] || colors.info}`;
                
                // 添加图标
                const icons = {
                    success: '✓',
                    error: '✕',
                    info: 'ℹ',
                    warning: '⚠'
                };
                
                notification.innerHTML = `
                    <div class="flex items-center space-x-2">
                        <span class="font-bold">${icons[type] || icons.info}</span>
                        <span>${message}</span>
                    </div>
                `;
                
                document.body.appendChild(notification);
                
                // 显示动画
                setTimeout(() => {
                    notification.classList.remove('translate-x-full');
                }, 100);
                
                // 自动隐藏
                setTimeout(() => {
                    notification.classList.add('translate-x-full');
                    setTimeout(() => {
                        if (notification.parentNode) {
                            notification.parentNode.removeChild(notification);
                        }
                    }, 300);
                }, type === 'error' ? 5000 : 3000); // 错误消息显示更长时间
            },
            
            // 批量验证表单
            validateForm() {
                // 清空之前的错误
                this.errors = {};
                
                // 验证所有字段
                const fields = ['name', 'phone', 'city', 'address', 'wechat', 'subject', 'age', 'notes'];
                fields.forEach(field => this.validateField(field));
                
                const isValid = Object.keys(this.errors).length === 0;
                
                if (!isValid) {
                    // 滚动到第一个错误字段
                    const firstErrorField = Object.keys(this.errors)[0];
                    const errorElement = document.querySelector(`[name="${firstErrorField}"]`);
                    if (errorElement) {
                        errorElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        errorElement.focus();
                    }
                }
                
                return isValid;
            },
            
            // 提交表单
            async submitForm() {
                if (!this.validateForm()) {
                    this.showNotification('请检查表单信息', 'error');
                    return;
                }
                
                this.loading = true;
                
                try {
                    const token = localStorage.getItem('token');
                    if (!token) {
                        //this.showNotification('请先登录', 'error');
                        //setTimeout(() => window.location.href = '/login', 1500);
                        //return;
                    }
                    
                    // 准备提交数据
                    const submitData = {
                        name: this.form.name,
                        phone: this.form.phone,
                        age: this.form.age ? parseInt(this.form.age) : null,
                        gender: this.form.gender,
                        city: this.form.city,
                        address: this.form.address,
                        wechat: this.form.wechat,
                        grade: this.form.grade,
                        subject: this.form.subject,
                        notes: this.form.notes
                    };
                    
                    const response = await fetch('/api/v1/customers', {
                        method: 'POST',
                        headers: {
                            'Authorization': 'Bearer ' + token,
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(submitData)
                    });
                    
                    if (!response.ok) {
                        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                    }
                    
                    const data = await response.json();
                    
                    if (data.code === 200) {
                        // 清除草稿
                        this.clearDraft();
                        
                        this.showNotification('客户添加成功', 'success');
                        
                        // 延迟1.5秒后自动跳转到客户列表页面
                        setTimeout(() => {
                            window.location.href = '/customers';
                        }, 1500);
                    } else {
                        // 处理服务器返回的错误
                        if (data.errors && typeof data.errors === 'object') {
                            this.errors = data.errors;
                            this.showNotification('表单验证失败，请检查输入', 'error');
                        } else {
                            throw new Error(data.message || '添加客户失败');
                        }
                    }
                } catch (error) {
                    console.error('Failed to create customer:', error);
                    this.showNotification(error.message || '网络错误，请稍后重试', 'error');
                } finally {
                    this.loading = false;
                }
            }
        }
    }
</script>
{{end}}